package com.pfizer.pfizerExpertForPad;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.pfizer.DB.DataHelper;
import com.pfizer.Entity.PCR;
import com.pfizer.Entity.UserInfo;
import com.pfizer.Entity.pNews;
import com.pfizer.Public.PublicFunc;
import com.pfizer.XmlContentHandler.SaxReadXml;

/**
 * 
 * PunchCardActivity--<b>打卡介面</b>
 * 
 * @author krui
 * @version 1.0 2011/11/22
 */
public class PunchCardActivity extends Activity implements OnClickListener {

	// final String serviceClassName =
	// "com.pfizer.pfizerExpertForPad.DataSyncService";
	Context mContext = null;

	Button[] btnPunch = new Button[10];
	ImageButton btntoMain = null;
	ImageButton btnNoticeBoard = null;
	UserInfo user = null;
	Bundle b = null;
	Thread thdRecordSearch = null;
	Thread thdRecordCreate = null;
	Handler handler = null;
	String PCR_ID = "";
	// GPS相關參數
	String serviceName;
	String bestProvider;
	LocationListener mLocationListener;
	LocationManager lm;
	Location location;
	boolean isGPSEnable;
	boolean isNetWorkEnable;

	pfizerApplication pApplication = null;
	private DataHelper dHelper;
	ProgressDialog progressDialog1;
	ProgressDialog progressDialog2;
	private String NewsUrlFormat = "%s/Pens_Api/DATA_FILE/News_Board.xml";
	private String PCRCreateUrlFormat = "%s/PENS_Api/Query.aspx?ProveCode=%s&Obj_ID=%s&Obj_From=%s&Which=PunchCardRecord_Create&UserID=%s&UserName=%s&Activity=%s&OnDuty_Lat=%s&OnDuty_Lng=%s";
	private String RecordSearchUrlFormat = "%s/PENS_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=PunchCardRecord_Search&UserID=%s&Bg_Date=Today&Ed_Date=Today";
	private String[] asButtonText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.punchcard);
		mContext = PunchCardActivity.this;
		InitApp initApp = new InitApp(mContext);
		initApp.SetApp(0);
		pApplication = (pfizerApplication) getApplicationContext();
		dHelper = pApplication.getDataHelper();
		asButtonText = getResources().getStringArray(R.array.punchButtonText);

		btnPunch[0] = (Button) findViewById(R.id.btnCard1_1);
		btnPunch[1] = (Button) findViewById(R.id.btnCard1_2);
		btnPunch[2] = (Button) findViewById(R.id.btnCard2_1);
		btnPunch[3] = (Button) findViewById(R.id.btnCard2_2);
		btnPunch[4] = (Button) findViewById(R.id.btnCard3_1);
		btnPunch[5] = (Button) findViewById(R.id.btnCard3_2);
		btnPunch[6] = (Button) findViewById(R.id.btnCard4_1);
		btnPunch[7] = (Button) findViewById(R.id.btnCard4_2);
		btnPunch[8] = (Button) findViewById(R.id.btnCard5_1);
		btnPunch[9] = (Button) findViewById(R.id.btnCard5_2);

		for (int i = 0; i < 10; i++) {
			btnPunch[i].setId(i + 1);
			btnPunch[i].setEnabled(false);
			btnPunch[i].setOnClickListener(this);
		}
		getPunchCardStatus();
		btntoMain = (ImageButton) findViewById(R.id.btnTomain);
		btnNoticeBoard = (ImageButton) this.findViewById(R.id.btnNoticeBoard);
		btntoMain.setOnClickListener(this);
		btnNoticeBoard.setOnClickListener(this);
		DataSyncAlarm.setPfizerMsgAlarm(this, pApplication
				.getMsgUpdInterValTime(), true);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				try {
					String Status = "";
					if (msg.what >= 0 && msg.what <= 6) {
						if (progressDialog1 != null) {
							progressDialog1.dismiss();
						}
						int iCnt = msg.what;
						int iPos = 0;
						Status = msg.getData().getString("Status");
						if (iCnt == 0) {
							iPos = 1;
						} else if (Status.equals("Create")) {
							iPos = 2 * iCnt;
						} else if (Status.equals("Complete")) {
							iPos = 2 * (iCnt + 1) - 1;
						}
						if (iPos > 11) {
							return;
						}
						for (int i = 0; i < iPos - 1; i++) {
							btnPunch[i].setEnabled(false);
							btnPunch[i].setText(String.format("%s(成功)",
									asButtonText[i]));
							btnPunch[i]
									.setBackgroundResource(R.drawable.card_active);
						}
						if (iPos - 1 < 10) {
							btnPunch[iPos - 1].setEnabled(true);
							for (int i = iPos; i < 10; i++) {
								btnPunch[i].setEnabled(false);
							}
						}

					} else {

						switch (msg.what) {
						case 9:
							if (progressDialog2 != null) {
								progressDialog2.dismiss();
							}
							Toast.makeText(mContext, "打卡連接建立成功！", 1).show();
							SystemClock.sleep(500);
							getPunchCardStatus();
							break;
						case -1:
							if (progressDialog1 != null) {
								progressDialog1.dismiss();
							}
							Toast.makeText(mContext, "連接服務器失敗！", 1).show();
							break;
						case -2:
							if (progressDialog2 != null) {
								progressDialog2.dismiss();
							}
							Toast.makeText(mContext, "打卡連接建立失敗！", 1).show();
							break;
						case 99:
							if (bestProvider != null) {
								// 设置定位后得到的location信息
								setCurrentLocation();
								lm.requestLocationUpdates(bestProvider, 1000,
										1, mLocationListener);
							}
							break;
						default:
							break;
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		};

		lm = getLocationManager();

		// 构造位置监听器
		mLocationListener = new LocationListener() {

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub

			}

			/**
			 * 当位置和安全设置-->使用无线网络和使用GPS卫星都选中时调用
			 */

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
			}

			/**
			 * 当位置和安全设置-->使用无线网络和使用GPS卫星都未选中时调用
			 */
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
			}

			/**
			 * 当位置信息变化时调用
			 */
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				if (location != null) {
					setCurrentLocation();
				} else {
					Toast.makeText(mContext, "暫時無法獲取您的位置信息，請到空曠處或者陽臺上重新登入本程式！",
							Toast.LENGTH_SHORT).show();
				}

			}
		};

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// 判断位置与安全设置中GPS与无线网络是否勾选
		isGPSEnable = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		isNetWorkEnable = lm
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		// 如果都没勾选GPS，进行设置
		if (!isGPSEnable && !isNetWorkEnable) {
			Toast.makeText(mContext, "請開啟GPS程式！", Toast.LENGTH_LONG).show();
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			startActivityForResult(intent, 0);
			return;
		}
		getLocationThread();
		SysnNewsData();
	}

	/**
	 * SysnNewsData：進行公告同步
	 */
	private void SysnNewsData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				InputStream inputStream = null;
				// Toast.makeText(mcontext, "同步公告", 1).show();
				String urlStr = String.format(NewsUrlFormat, pApplication
						.getWebUrl());
				// urlStr = "http://222.196.236.62/xml/news.xml";
				// dbHelper.setLpDateTime();
				try {
					// 取得服務器上公告的Stream數據
					URL url = new URL(urlStr);
					inputStream = url.openStream();
				} catch (IOException ex) {
					// Toast.makeText(mcontext, "取得公告數據失敗", 1).show();
					return;
				}
				try {
					// 通過sax解析Stream取得xml公告列表
					List<pNews> newsList = SaxReadXml.readNews(inputStream);
					int iLen = newsList.size();
					pNews pnews;
					for (int i = 0; i < iLen; i++) {
						pnews = newsList.get(i);
						// 判斷該公告是否已經存在，若不存在則添加
						if (!dHelper.isExistsNewsByID(pnews.getID())) {
							dHelper.addNews(pnews);
						}
					}
				} catch (Exception ex) {
					// Toast.makeText(mcontext, "同步公告數據失敗", 1).show();
					return;
				}
			}
		});
	}
	
	private void getLocationThread() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (bestProvider == null) {
					Criteria criteria = new Criteria();
					criteria.setAccuracy(Criteria.ACCURACY_COARSE);
					criteria.setPowerRequirement(Criteria.POWER_LOW);
					criteria.setAltitudeRequired(false);
					criteria.setBearingRequired(false);
					criteria.setSpeedRequired(false);
					criteria.setCostAllowed(true);
					bestProvider = lm.getBestProvider(criteria, true);
					// LocationProvider的异常处理
					if (bestProvider == null) {
						bestProvider = LocationManager.NETWORK_PROVIDER;
					}
					if (bestProvider == null) {
						SystemClock.sleep(4 * 1000);
					}
				}
				Message msg = new Message();
				msg.what = 99;
				handler.sendMessage(msg);
			}
		}).start();
	}

	@Override
	protected void onResume() {// 必须在onResume中注册监听
		// TODO Auto-generated method stub
		super.onResume();
		if (bestProvider != null) {
			lm.requestLocationUpdates(bestProvider, 1000, 1, mLocationListener);
		}
		TextView tvDate = (TextView) this.findViewById(R.id.tvDate);
		Date dt = new Date();
		tvDate.setText(String.format("%d/%d/%d", dt.getYear() + 1900, dt
				.getMonth() + 1, dt.getDate()));
	}

	@Override
	protected void onPause() {// 反注册
		// TODO Auto-generated method stub
		super.onPause();
		if (lm != null) {
			lm.removeUpdates(mLocationListener);
		}
	}

	/**
	 * 设置得到的location信息
	 * 
	 * @param location
	 */
	private void setCurrentLocation() {
		// 同一時刻要麼上班打卡，要麼下班打卡，在獲取到位置信息同時設置on跟off座標是因為獲取GPS只在punchCardActivity頁面進行，而完成打卡需要上傳off的座標是在dialog那個介面，所以在這裡同時設置位置，再傳遞到另一個activity
		try {
			boolean gpsStatus = lm
					.isProviderEnabled(LocationManager.GPS_PROVIDER);
			pApplication.setDuty_Lat(0);
			pApplication.setDuty_Lng(0);
			this.location = null;
			if (gpsStatus) {
				if (bestProvider != null) {
					Location currentlocation = lm
							.getLastKnownLocation(bestProvider);
					if (currentlocation != null) {
						this.location = currentlocation;
						pApplication.setDuty_Lat(currentlocation.getLatitude());
						pApplication
								.setDuty_Lng(currentlocation.getLongitude());
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(mContext, "暫時無法獲取您的位置信息，請到空曠處或者陽臺上重新登入本程式！",
					Toast.LENGTH_SHORT).show();
			return;
		}
	}

	/**
	 * 获取位置管理对象实例
	 * 
	 * @return 实例化对象
	 */
	private LocationManager getLocationManager() {
		LocationManager lm;
		serviceName = Context.LOCATION_SERVICE;
		// 获得locationmanager实例
		lm = (LocationManager) getSystemService(serviceName);
		return lm;
	}

	private void getPunchCardStatus() {
		progressDialog1 = ProgressDialog.show(mContext, null,
				"正在獲取打卡狀況，請稍後...", true, false);

		try {
			thdRecordSearch = new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					String urlStr = String.format(RecordSearchUrlFormat,
							pApplication.getWebUrl(), pApplication
									.getMainProveCode(), pApplication
									.getObjFrom(), pApplication.getObjID(),
							pApplication.getUserID());
					InputStream inputStream = null;
					try {
						URL url = new URL(urlStr);
						// inputStream = url.openStream();
						HttpURLConnection urlCon = (HttpURLConnection) url
								.openConnection();
						urlCon.setConnectTimeout(10 * 1000);
						urlCon.setReadTimeout(10 * 1000);
						int responseCode = urlCon.getResponseCode();
						if (responseCode == HttpURLConnection.HTTP_OK) {
							inputStream = urlCon.getInputStream();
						}
					} catch (IOException e) {
						// TODO: handle exception
						Message msg = new Message();
						msg.what = -1;
						msg.getData().putString("error", "連接服務器失敗！");
						handler.sendMessage(msg);
						return;
					}

					try {
						List<PCR> pcrs = SaxReadXml.readPCR(inputStream);
						PCR pcr = null;
						String Status = "";

						int Len = pcrs.size();
						Message msg = new Message();
						Bundle b = new Bundle();
						if (Len == 0) {
							msg.what = 0;
							handler.sendMessage(msg);
						} else {
							msg.what = Len;
							pcr = pcrs.get(0);
							Status = pcr.getStatus();
							PCR_ID = String.valueOf(pcr.getPCR_ID());
							b.putString("Status", Status);
							msg.setData(b);
							handler.sendMessage(msg);
							pcr = null;
						}
						pcrs = null;
					} catch (Exception e) {
						// TODO: handle exception
						Message msg = new Message();
						msg.what = 0;// 沒獲取到數據就只能點擊第一次上班打卡
						msg.getData().putString("error", e.getMessage());
						handler.sendMessage(msg);
					}
				}

			});
			thdRecordSearch.start();
		} catch (Exception e) {
			// TODO: handle exception

		}
	}

	

	private void CreatePunchCard() {
		if ((this.location == null)
				|| (pApplication.getDuty_Lat() == 0 && pApplication
						.getDuty_Lat() == 0)) {
			Toast.makeText(mContext, "暫時無法獲取您的位置信息，請到空曠處或者陽臺上重新登入本程式！", 1)
					.show();
			return;
		}
		progressDialog2 = ProgressDialog.show(mContext, null,
				"正在建立打卡連接，請稍後...", true, false);

		try {
			thdRecordCreate = new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					String urlStr = String.format(PCRCreateUrlFormat,
							pApplication.getWebUrl(), pApplication
									.getMainProveCode(), pApplication
									.getObjID(), pApplication.getObjFrom(),
							pApplication.getUserID(), pApplication
									.getUserName(), "看診", pApplication
									.getDuty_Lat(), pApplication.getDuty_Lng());
					try {
						URL url = new URL(urlStr);
						HttpURLConnection urlCon = (HttpURLConnection) url
								.openConnection();
						urlCon.setConnectTimeout(10 * 1000);
						urlCon.setReadTimeout(10 * 1000);
						int responseCode = urlCon.getResponseCode();
						String resultString = "";
						if (responseCode == HttpURLConnection.HTTP_OK) {
							resultString = PublicFunc.inputStream2String(urlCon
									.getInputStream());
						}

						// 如果獲取到的字符為Y，則已經查看，更新本地數據
						try {
							long l = new Long(resultString).longValue();
							PCR_ID = resultString;
							Message msg = new Message();
							msg.what = 9;
							handler.sendMessage(msg);
						} catch (Exception e) {
							// TODO: handle exception
							Message msg = new Message();
							PCR_ID = "";
							msg.what = -2;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						// TODO: handle exception
						Message msg = new Message();
						msg.what = -2;
						PCR_ID = "";
						handler.sendMessage(msg);
					}
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
			Message msg = new Message();
			PCR_ID = "";
			msg.what = -2;
			handler.sendMessage(msg);

		}
		thdRecordCreate.start();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 101:
			if (resultCode == RESULT_OK) {
				getPunchCardStatus();
			}
			break;
		}
	}

	/**
	 * 對相關控件設置監聽處理事件
	 * 
	 * @author krui
	 * @see android.view.View.OnClickListener
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int Id = v.getId();
		if (Id >= 0 && Id <= 10) {
			if (Id % 2 == 1) {
				CreatePunchCard();
			} else {
				if ((this.location == null)
						|| (pApplication.getDuty_Lat() == 0 && pApplication
								.getDuty_Lat() == 0)) {
					Toast.makeText(mContext, "暫時無法獲取您的位置信息，請到空曠處或者陽臺上重新登入本程式！",
							1).show();
					return;
				} else {
					Intent intent1_2 = new Intent(mContext,
							PunchCardDialog.class);
					intent1_2.putExtra("PCR_ID", PCR_ID);
					startActivityForResult(intent1_2, 101);
				}
			}
		} else {

			switch (Id) {
			case R.id.btnTomain:
				Intent intentToMian = new Intent(mContext, MainActivity.class);
				startActivity(intentToMian);
				break;
			case R.id.btnNoticeBoard:
				Intent intentToNews = new Intent(mContext,
						NoticeBoardActivity.class);
				startActivity(intentToNews);
				break;
			default:
				break;
			}
		}
	}

	@Override
	// 监听退出键
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			new AlertDialog.Builder(mContext).setTitle("離開程式").setMessage(
					"確定離開嗎？").setPositiveButton("確定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

							Date dt = new Date();
							DataHelper dataHelper = pApplication
									.getDataHelper();
							dataHelper.setLoopCount(0, dt.getTime());
							DataSyncAlarm.setDataSyncAlarm(mContext, true, dt
									.getTime() + 10 * 1000);
							pApplication.setUserID("");
							pApplication.setUserName("");
							finish();
						}
					}).setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					}).show();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mContext = null;
		btnPunch = null;
		btntoMain = null;
		btnNoticeBoard = null;
		user = null;
		b = null;
		pApplication = null;
	}

}
